package com.cloudxingkong.dianyinke.Student.Ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudxingkong.dianyinke.NewTeacher.Utils.CookieHelper;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.LoginJsonUtils;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.UploadUtils;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.Student.Adapter.MSListviewAdapter;
import com.cloudxingkong.dianyinke.Student.Utils.MySwipeView;
import com.cloudxingkong.dianyinke.Student.bean.MSTest;
import com.cloudxingkong.dianyinke.Uri.studentUri.StudentUri;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;
import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * 我的地址
 */
public class MySite extends BaseActivity implements AdapterView.OnItemClickListener, MSListviewAdapter.onTouchDelete, SwipeRefreshLayout.OnRefreshListener {

    private ListView listView;
    private List<MSTest.ListBean> list;
    private MSListviewAdapter adapter;
    private SharedPreferences sharedPreferences;
    private SwipeRefreshLayout swipeRefreshLayout;
    private String sessionid;
    private boolean isDelete = false;
    private static final String getAddr = ThisUri.SERVER_YUMING + StudentUri.MYSITE;
    private int anInt;

    @Override
    protected void onCreateView(Bundle savedInstanceState) {
        super.onCreateView(savedInstanceState);
        setContentView(R.layout.activity_my_site);
        init();
        loadData();
        listView.setOnItemClickListener(this);
    }

    private void init() {
        sharedPreferences = MySite.this.getSharedPreferences("data_dyk", 0);
        sessionid = CookieHelper.getSessionID(sharedPreferences);
        listView = (ListView) findViewById(R.id.ms_listview);
        list = new ArrayList<>();
        adapter = new MSListviewAdapter(list, this, listView, this);
        listView.setAdapter(adapter);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.srl_mysite);

        swipeRefreshLayout.setOnRefreshListener(this);
        //设置自动刷新
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
                swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
                        android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);

            }
        });
    }

    private void loadData() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                UploadUtils.getData(getAddr, sessionid, new UploadUtils.UploadCallback() {
                    @Override
                    public void onFinish(String state) {
                        Message msg = handler.obtainMessage();
                        msg.what = 1;
                        msg.obj = state;
                        handler.sendMessage(msg);
                    }
                });
            }
        }.start();
    }

    //返回按钮
    public void back(View view) {
        finish();
    }

    //添加行地址
    public void addNewAddress(View view) {
        Intent intent = new Intent(MySite.this, AddSite.class);
        startActivity(intent);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //  Toast.makeText(this,position+"",Toast.LENGTH_SHORT).show();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    String state = (String) msg.obj;
                    if (state != null && !state.equals("")) {
                        Gson gson = new Gson();
                        MSTest msTest = gson.fromJson(state, MSTest.class);
                        list.addAll(msTest.getList());
                        //创建设配器
                        adapter.notifyDataSetChanged();
                        swipeRefreshLayout.setRefreshing(false);
                    }
                    break;
                case 2:
                    Toast.makeText(MySite.this, "删除失败!", Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    Toast.makeText(MySite.this, "删除成功!", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    public void onDelete(TextView deleteView, final int position) {
        deleteView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                int id = list.get(position).getId();
                RequestParams params = new RequestParams(ThisUri.SERVER_YUMING + StudentUri.DELETE_ADDR);
                params.addHeader("cookie", sessionid);
                params.addBodyParameter("addrid", id + "");

                x.http().post(params, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {

                        Log.e("test", "删除地址的结果 " + result);

                        Object success = LoginJsonUtils.getJsonFromLogin(result).get("success");

                        isDelete = (boolean) success;
                        if (isDelete) {
                            String position2 = (String) v.getTag();
                            ((MySwipeView) v.getParent()).quickClose();
                            list.remove(Integer.parseInt(position2));
                            adapter.notifyDataSetChanged();
                            handler.sendEmptyMessage(3);
                        } else {
                            handler.sendEmptyMessage(2);
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 555) {
            if (resultCode == 666) {
                loadData();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRefresh() {
        list.clear();
        loadData();
    }

    public void onTouch(int postion) {
        anInt = postion;
    }
}
